﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;
using com.lover.astd.common.manager;

namespace com.lover.astd.common.partner.impl
{
    public class BaiduLogin : LoginImplBase
    {
        public BaiduLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra=null)
        {
            LoginResult result = new LoginResult();
            logging();
            HttpResult resp;

            string token_url = String.Format(
                "https://passport.baidu.com/v2/api/?getapi&tpl=mn&apiver=v3&tt={0}&class=login&logintype=dialogLogin&callback=bd__cbs__apsigl", 
                TimeMgr.TimeStamp);
            resp = TransferMgr.doGetPure(token_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            // 这里需要取token两次, 第一次设置一个cookie, 第二次才能取到token
            resp = TransferMgr.doGetPure(token_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }

            string content = resp.getContent();
            Regex re = new Regex("\"token\"\\s*:\\s*\"(.*?)\"");
            Match m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            string token = m.Groups[1].Value;
            if (token == null || token == "") { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }

            string loginurl = "https://passport.baidu.com/v2/api/?login";
            string data = String.Format(
                "staticpage=http%3A%2F%2Fwww.baidu.com%2Fcache%2Fuser%2Fhtml%2Fv3Jump.html&charset=UTF-8&token={0}&tpl=mn&apiver=v3&tt={1}&codestring={2}&safeflg=0&u=http%3A%2F%2Fwww.baidu.com%2F&isPhone=false&quick_user=0&loginmerge=true&logintype=dialogLogin&splogin=rate&username={3}&password={4}&verifycode={5}&mem_pass=on&ppui_logintime=180209&callback=parent.bd__pcbs__uvdb8z",
                token, TimeMgr.TimeStamp, extra == null ? "" : extra, _username, _password, verify_code == null ? "" : verify_code);
            resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            content = resp.getContent();
            if(!content.Contains("err_no=0"))
            {
                if (content.Contains("&codeString="))
                {
                    re = new Regex("&codeString=([^=&]*?)&");
                    m = re.Match(content);
                    if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
                    string vcode_string = m.Groups[1].Value;

                    result.StatusCode = LoginStatusCode.NeedVerifyCode;
                    result.ErrMessage = "需要输入验证码";
                    result.CaptchaUrl = "https://passport.baidu.com/cgi-bin/genimage?" + vcode_string;
                    result.CaptchaExtra = vcode_string;
                    result.CaptchaImage = LoginMgr.getInstance().getCaptchaImage(result.CaptchaUrl, ref cookies);
                    result.WebCookies = cookies;
                    return result;
                }
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }

            string redirecturl = String.Format("http://youxi.baidu.com/login_game_by_post.xhtml?id=177&serverId=S{0}&frameFlag=true&source=31", _acc.ServerId);
            resp = TransferMgr.doGetPure(redirecturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGotoGameUrl; return result; }
            content = resp.getContent();

            re = new Regex("oForm\\.action\\s*?=\\s*?\"(http:\\/\\/s.*?)\"");
            m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }
            string action = m.Groups[1].Value;
            re = new Regex("oInput\\.value\\s*?=\\s*?\"([^\"']*?)\"");
            MatchCollection matches = re.Matches(content);
            if (matches == null || matches.Count < 10) { result.StatusCode = LoginStatusCode.FailInGetToken; return result; }

            string user_id = matches[0].Groups[1].Value;
            string api_key = matches[1].Groups[1].Value;
            string server_id = matches[2].Groups[1].Value;
            string invite_id = matches[3].Groups[1].Value;
            string client = matches[4].Groups[1].Value;
            string cm_flag = matches[5].Groups[1].Value;
            string timestamp = matches[6].Groups[1].Value;
            string showlogintype = matches[7].Groups[1].Value;
            string sign = matches[8].Groups[1].Value;
            string screen = matches[9].Groups[1].Value;
            timestamp = Uri.EscapeDataString(timestamp);
            timestamp = timestamp.Replace("%20", "+");
            //user_id=317206549&api_key=2a31743e012a62517a50123f36f6b822&server_id=S33&cm_flag=n&timestamp=2014-02-14+13%3A17%3A20&sign=88037011E4522B3700F0A7F887DB88E1
            string p_data = String.Format("user_id={0}&api_key={1}&server_id={2}&cm_flag={3}&timestamp={4}&sign={5}",
                user_id, api_key, server_id, cm_flag, timestamp, sign);

            postStartGame(action, p_data, result, ref cookies);
            return result;
        }
    }
}
